package com.zzzzzz.account.signin;

import javax.annotation.Resource;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.zzzzzz.account.user.User;
import com.zzzzzz.account.user.UserBase;
import com.zzzzzz.account.user.UserDao;

@Service("onlineService")
public class OnlineServiceImpl implements OnlineService{
	
	@Resource
	private UserDao userDao;
	
	private static Logger logger = LoggerFactory.getLogger(OnlineServiceImpl.class);
	
	public Boolean isSignedIn() {
		try{
			Subject currentUser = SecurityUtils.getSubject();
			return currentUser.isAuthenticated();
		}catch(Exception e){
			logger.warn("isSignedIn", e);
			return false;
		}
	}

	public User findUser() throws NoSuchOnlineUserException {
		String userId = this.findUserId();
		User user = userDao.findById(userId);
		return user;
	}

	public UserBase findUserBase() throws NoSuchOnlineUserException {
		String userId = this.findUserId();
		UserBase userBase = userDao.findUserBaseById(userId);
		return userBase;
	}
	
	public String findUserId() throws NoSuchOnlineUserException {
		Object userIdObj = SecurityUtils.getSubject().getPrincipal();
		if(userIdObj == null) throw new NoSuchOnlineUserException();
		return SecurityUtils.getSubject().getPrincipal().toString();
	}
	
}
